/**
 * @Author: grainbuds
 * @CreateDate: 2023-08-07 11:28:10 星期一
 * @Description: api.go
 */
package redis

import (
	redigo "github.com/gomodule/redigo/redis"
	"time"
)

var client *RedisClient

type RedisClient struct {
	pool *redigo.Pool
}

func init() {
	setup()
}

func setup() error {
	client = &RedisClient{}
	client.pool = &redigo.Pool{
		//最大空闲连接数
		MaxIdle: 30,
		//在给定时间内，允许分配的最大连接数（当为零时，没有限制）
		MaxActive: 30,
		//在给定时间内，保持空闲状态的时间，若到达时间限制则关闭连接（当为零时，没有限制）
		IdleTimeout: 200,
		//提供创建和配置应用程序连接的一个函数
		Dial: func() (redigo.Conn, error) {
			c, err := redigo.Dial("tcp", "127.0.0.1:6379")
			if err != nil {
				return nil, err
			}
			//如果redis设置了用户密码，使用auth指令
			/*
				if _, err := c.Do("AUTH", ""); err != nil {
					c.Close()
					return nil, err
				}
			*/
			return c, err
		},
		TestOnBorrow: func(c redigo.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
	return nil
}

func GetClusterRedisClient() *RedisClient {
	return client
}

func (rc RedisClient) ScriptLoad(script string) (string, error) {
	conn := rc.pool.Get()
	cmdArgs := make([]interface{}, 0)
	cmdArgs = append(cmdArgs, "load")
	cmdArgs = append(cmdArgs, script)
	return redigo.String(conn.Do("script", cmdArgs...))
}

func (rc RedisClient) EvalSha(sha1 string, keys []string, args ...interface{}) (interface{}, error) {
	conn := rc.pool.Get()
	cmdArgs := make([]interface{}, 0)
	cmdArgs = append(cmdArgs, sha1)
	cmdArgs = append(cmdArgs, len(keys))
	for _, key := range keys {
		cmdArgs = append(cmdArgs, key)
	}
	cmdArgs = append(cmdArgs, args...)
	return conn.Do("evalsha", cmdArgs...)
}

func (rc RedisClient) ScriptFlush() (string, error) {
	conn := rc.pool.Get()
	return redigo.String(conn.Do("script flush"))
}
